import { IUIEngineInputParam } from '@/core/interface';
import { UIEngine } from './ui-engine';

/**
 * 项显示
 *
 * @export
 * @class ItemUIEngine
 * @extends {UIEngine<A>}
 * @template A
 */
export class ItemUIEngine<A> extends UIEngine<A> {
	/**
	 * 设置项显示
	 *
	 * @param {IUIEngineInputParam<A>} args
	 * @return {*}
	 * @memberof ItemUIEngine
	 */
	setItemVisible(args: IUIEngineInputParam<A>) {
		const { itemName } = this.rowData;
		const result = this.executeScriptCode(args);
		const { detailModel } = args;
		const itemDetail: any = detailModel?.find((item: any) => {
			return item.name == itemName;
		});
		if (!itemDetail) {
			return;
		}
		itemDetail.visible = result !== undefined ? result : itemDetail.visible;
	}

	/**
	 * 设置项启用
	 *
	 * @param {IUIEngineInputParam<A>} args
	 * @return {*}
	 * @memberof ItemUIEngine
	 */
	setItemDisabled(args: IUIEngineInputParam<A>) {
		const { itemName } = this.rowData;
		const result = this.executeScriptCode(args);
		const { detailModel } = args;
		const itemDetail: any = detailModel?.find((item: any) => {
			return item.name == itemName;
		});
		if (!itemDetail) {
			return;
		}
		itemDetail.disabled = result !== undefined ? result : itemDetail.disabled;
	}

	/**
	 * 设置项必填
	 *
	 * @param {IUIEngineInputParam<A>} args
	 * @return {*}
	 * @memberof ItemUIEngine
	 */
	setItemRequired(args: IUIEngineInputParam<A>) {
		const { itemName } = this.rowData;
		const result = this.executeScriptCode(args);
		const { detailModel } = args;
		const itemDetail: any = detailModel?.find((item: any) => {
			return item.name == itemName;
		});
		if (!itemDetail) {
			return;
		}
		itemDetail.required = result !== undefined ? result : itemDetail.required;
	}

	/**
	 * 执行脚本
	 *
	 * @param {IUIEngineInputParam<A>} args
	 * @return {*}  {(boolean | undefined)}
	 * @memberof ItemUIEngine
	 */
	executeScriptCode(args: IUIEngineInputParam<A>): boolean | undefined {
		const { scriptCode } = this.rowData;
		if (!scriptCode) {
			return undefined;
		}
		const { navParam: viewparam, navContext: context, data: _data } = args;
		const data = (_data && _data.length > 0 && _data[0]) || {};
		const env = App.getProjectSetting();
		try {
			return eval(scriptCode);
		} catch (error) {
			console.warn(`执行脚本界面逻辑异常，脚本代码为：${scriptCode}`);
			return undefined;
		}
	}

	/**
	 * 设置项逻辑
	 *
	 * @param {IUIEngineInputParam<A>} args
	 * @memberof ItemUIEngine
	 */
	public executeItemLogic(args: IUIEngineInputParam<A>) {
		const { triggerType } = this.rowData;
		switch (triggerType) {
			case 'ITEMVISIBLE':
				this.setItemVisible(args);
				break;
			case 'ITEMENABLE':
				this.setItemDisabled(args);
				break;
			case 'ITEMBLANK':
				this.setItemRequired(args);
				break;
		}
	}
}
